#!/usr/bin/env bash

############################################################################
#
# 远程执行该脚本，请在命令行中直接执行以下命令：
#
#   curl -sSL https://gitee.com/tay3223/biubiubiu/raw/master/kubernetes/init/init.sh | /bin/bash
#
#
############################################################################




# k8s版本
VERSION="1.26.5"

# 本机IP地址
IP=$(hostname -I | awk '{print $1}')


# 声明一个字典用来存放机器名和ip地址的映射
declare -A dict

# 字典声明时赋值
#dict=(["192.168.55.220"]="k8s-master" ["192.168.55.201"]="k8s-node1" ["192.168.55.202"]="k8s-node2")

# 字典动态追加赋值
dict["192.168.55.230"]="k8s-master"
dict["192.168.55.201"]="k8s-node1"
dict["192.168.55.202"]="k8s-node2"
dict["192.168.55.203"]="k8s-node3"

# 打印当前地址
echo "${dict[$IP]}"





###############################################
# 修改主机名（通过本机的ip地址，拿到上面预先映射好的主机名）
hostnamectl set-hostname "${dict[$IP]}"



#######################################
# 把集群的机器和ip映射写进到本地hosts中
cat >> /etc/hosts << EOF

192.168.55.230 k8s-master
192.168.55.201 k8s-node1
192.168.55.202 k8s-node2
192.168.55.203 k8s-node3

EOF



###############################################
# 关闭现有防火墙和SELinux
systemctl disable firewalld && systemctl stop firewalld
systemctl disable iptables && systemctl stop iptables
firewall-cmd --state

#永久关闭SELinux
getenforce
setenforce 0
sed -i '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config



###############################################
# 时间同步
yum -y install ntpdate
/usr/sbin/ntpdate time1.aliyun.com
(crontab -l; echo "0 */1 * * * /usr/sbin/ntpdate time1.aliyun.com") | crontab



###############################################
# 内核转发、网桥过滤
cat > /etc/sysctl.d/k8s.conf << EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
vm.swappiness = 0
EOF

# 加载br_netfilter模块
modprobe br_netfilter
lsmod | grep br_netfilter

# 加载网桥过滤及内核转发文件
sysctl -p /etc/sysctl.d/k8s.conf



###############################################
# 安装ipset及ipvsadm
yum -y install ipset ipvsadm

# 配置ipvsadm模块加载方式，添加需要加载的模块
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack
EOF

# 授权、运行、检查是否加载
chmod 755 /etc/sysconfig/modules/ipvs.modules \
    && bash /etc/sysconfig/modules/ipvs.modules \
    && lsmod | grep -e ip_vs -e nf_conntrack



###############################################
# 关闭swap分区
swapoff -a
sed -i 's/.*swap.*/#&/g' /etc/fstab
cat /etc/fstab




###############################################
# 安装docker
# （此处略过，机器都已经预先安装好了）




###############################################
# cri-dockerd安装
wget https://osoc.oss-cn-shanghai.aliyuncs.com/bao/docker/cri-dockerd-0.3.1-3.el7.x86_64.rpm
rpm -ivh cri-dockerd-0.3.1-3.el7.x86_64.rpm

# 修改镜像地址为国内，否则kubelet拉取不了镜像导致启动失败
# vim /usr/lib/systemd/system/cri-docker.service
# ExecStart=/usr/bin/cri-dockerd --container-runtime-endpoint fd:// --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.7
#（这里直接导入下面整个文件，避免替换时出错）
# 先备份一下
cp /usr/lib/systemd/system/cri-docker.service /usr/lib/systemd/system/cri-docker.service.bak
# 这里直接导入完整的配置
cat > /usr/lib/systemd/system/cri-docker.service <<EOF
[Unit]
Description=CRI Interface for Docker Application Container Engine
Documentation=https://docs.mirantis.com
After=network-online.target firewalld.service docker.service
Wants=network-online.target
Requires=cri-docker.socket

[Service]
Type=notify
ExecStart=/usr/bin/cri-dockerd --container-runtime-endpoint fd:// --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.7
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always

# Note that StartLimit* options were moved from "Service" to "Unit" in systemd 229.
# Both the old, and new location are accepted by systemd 229 and up, so using the old location
# to make them work for either version of systemd.
StartLimitBurst=3

# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd 230.
# Both the old, and new name are accepted by systemd 230 and up, so using the old name to make
# this option work for either version of systemd.
StartLimitInterval=60s

# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

# Comment TasksMax if your systemd version does not support it.
# Only systemd 226 and above support this option.
TasksMax=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF





###############################################
# 启动cri-dockerd
systemctl daemon-reload
systemctl enable cri-docker && systemctl start cri-docker






###############################################
#配置k8s国内加速yum源
cat > /etc/yum.repos.d/kubernetes.repo << EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF





###############################################
#安装基座组件
yum install -y  "kubelet-${VERSION}"  "kubeadm-${VERSION}"  "kubectl-${VERSION}"
systemctl daemon-reload
systemctl enable kubelet && systemctl restart kubelet





###############################################
#配置kubelet
sed -i '/^KUBELET_EXTRA_ARGS=/c KUBELET_EXTRA_ARGS="--cgroup-driver=systemd"' /etc/sysconfig/kubelet




###############################################
# 提示
cat << \EOF

执行以下命令，启动cri-dockerd
    # systemctl daemon-reload
    # systemctl enable cri-docker && systemctl start cri-docker

    设置kubelet为开机自启动即可，由于没有生成配置文件，集群初始化后自动启动
    # systemctl enable kubelet && systemctl restart kubelet

必须得先启动上面的服务，再开始初始化集群


（一键复制版）
systemctl daemon-reload \
    && systemctl enable cri-docker \
    && systemctl start cri-docker \
    && systemctl enable kubelet \
    && systemctl restart kubelet
EOF
